from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.sql import func
from datetime import datetime, timedelta
from app.database import Base


class VerificationCode(Base):
    """验证码模型类
    
    用于存储密码重置验证码
    """
    __tablename__ = "verification_codes"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    code = Column(String(6), nullable=False)  # 6位数字验证码
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    expires_at = Column(DateTime(timezone=True), nullable=False)  # 过期时间
    is_used = Column(Integer, default=0)  # 是否已使用，0-未使用，1-已使用
    
    @classmethod
    def create_code(cls, user_id, code, expires_minutes=10):
        """创建新的验证码
        
        Args:
            user_id: 用户ID
            code: 验证码
            expires_minutes: 过期时间（分钟）
            
        Returns:
            VerificationCode: 验证码对象
        """
        expires_at = datetime.now() + timedelta(minutes=expires_minutes)
        return cls(
            user_id=user_id,
            code=code,
            expires_at=expires_at
        )